/*
 * File name: WatermarkManager.java
 * 
 * Description: The class provides a simple interface to the mosaic algorithm.
 *              The class allows passing watermark frame and picture captured to be
 *              stitched together, and then stitches and blends them together into
 *              a single output which can then be accessed as a single image. 
 *
 * Author: Theobald_wu, contact with wuqizhi@tydtech.com
 * 
 * Date: 2014-4-29   
 * 
 * Copyright (C) 2014 TYD Technology Co.,Ltd.
 * 
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.freeme.cameraplugin.posemode;

import java.util.ArrayList;
import java.util.List;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.Drawable;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.LayoutInflater.Factory;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.freeme.camera.BasePluginImpl;
import com.freeme.camera.CameraInterfaceManage;
import com.freeme.camera.ICameraExt;
import com.freeme.cameraplugin.posemode.ui.Rotatable;
import com.freeme.cameraplugin.posemode.model.PoseResouceId;
import com.freeme.cameraplugin.posemode.model.PosetemInfo;
import com.freeme.cameraplugin.posemode.ui.PosePreviewPanel;
import com.freeme.cameraplugin.posemode.ui.PoseViewPager;
import com.freeme.cameraplugin.posemode.ui.RotataTextView;
import com.freeme.cameraplugin.posemode.ui.RotateImageView;
import com.freeme.cameraplugin.posemode.ui.RotateLayout;
import com.freeme.cameraplugin.posemode.utils.PoseUtil;
import com.freeme.elementscenter.agent.ECOfflineUtil;

@SuppressLint("InflateParams")
public class PoseMode extends BasePluginImpl {
    private static final String TAG = "[TYD_DEBUG]PoseManager";
    public static final int OUTPUT_IMAGE_WIDTH_IDEAL = 1728;
    public static final int OUTPUT_IMAGE_HEIGHT_IDEAL = 2272;
    private float mPreviewScale; // base on output
    private int mOrientation;
    private SharedPreferences mSharedPref;

    private String mAddr;
    private String mCurrItemId;
    private LayoutInflater mLayoutInflater;
    private ICameraExt mCameraExt = null;

    private List<PosetemInfo> mPreviewItemList = new ArrayList<PosetemInfo>();

    private PosePreviewPanel mPreviewPanel;
    private ViewGroup mRootView;
    private String mPackageName;
    private LinearLayout mTextEcDownLoad;

    @Override
    public int getModuleID() {
        return 100;
    }

    @Override
    public String getPkgName() {
        return mPackageName;
    }

    @Override
    public Drawable getModuleIcon() {
        return mContext.getResources().getDrawable(R.drawable.entry_icon);
    }

    @Override
    public String getModuleTitle() {
        return mContext.getString(R.string.app_name);
    }

    @Override
    public void showPanel(ViewGroup root) {
        mCameraExt = CameraInterfaceManage.getInstance().cameraExt;
        if (root != null) {
            show(root);
        }
    }

    @Override
    public void hidePanel() {
        hide();
    }

    @Override
    public void switchPanel(ViewGroup root) {
    }

    @Override
    public void onOrientationChanged(int orientation) {
        Log.i(TAG, "orientation = " + orientation);
        if (isShowGuide()) {
            return;
        }

        synchronized (PoseMode.this) {
            if (mOrientation != orientation) {
                mOrientation = orientation;
                setOrientation(mPreviewPanel, mOrientation, true);
            }
        }
    }

    private void setOrientation(View view, int orientation, boolean animation) {
        if (view == null) {
            return;
        }
        if (view instanceof Rotatable) {
            ((Rotatable) view).setOrientation(orientation, animation);
        } else if (view instanceof ViewGroup) {
            ViewGroup group = (ViewGroup) view;
            for (int i = 0, count = group.getChildCount(); i < count; i++) {
                setOrientation(group.getChildAt(i), orientation, animation);
            }
        }
    }

    @Override
    protected void onRelease() {
    }

    @Override
    public byte[] blendOutput(byte[] jpegData) {
        return null;
    }

    public String getCurrItemId() {
        return mCurrItemId;
    }

    public void setCurrItemId(String id) {
        mCurrItemId = id;
    }

    public List<PosetemInfo> getPreviewItemList() {
        return mPreviewItemList;
    }

    private void addItemToPreviewItemList(PosetemInfo info) {
        mPreviewItemList.add(info);
    }

    public void clearPreviewItemList() {
        mPreviewItemList.clear();
    }

    public int getCurrItemPageIndex() {
        int index = 0;
        for (int i = 0; i < mPreviewItemList.size(); i++) {
            PosetemInfo itemInfo = mPreviewItemList.get(i);
            String id = String.valueOf(itemInfo.thumbnailId) + itemInfo.thumbnailUrl;
            if (mCurrItemId.equals(id)) {
                index = i;
                break;
            }
        }
        return index;
    }

    private PosetemInfo copyWatermarkItemInfo(PosetemInfo itemInfo) {
        PosetemInfo info = new PosetemInfo();
        info.layoutId = itemInfo.layoutId;
        info.thumbnailId = itemInfo.thumbnailId;
        info.primitiveId = itemInfo.primitiveId;
        info.promptId = itemInfo.promptId;
        info.thumbnailUrl = itemInfo.thumbnailUrl;
        info.primitiveUrl = itemInfo.primitiveUrl;
        info.prompt = itemInfo.prompt;
        info.type = itemInfo.type;
        return info;
    }

    public void replacePreviewItem(PosetemInfo itemInfo) {
        for (PosetemInfo info : mPreviewItemList) {
            if (info.type.equals(itemInfo.type)) {
                info.layoutId = itemInfo.layoutId;
                info.thumbnailId = itemInfo.thumbnailId;
                info.primitiveId = itemInfo.primitiveId;
                info.promptId = itemInfo.promptId;
                info.thumbnailUrl = itemInfo.thumbnailUrl;
                info.primitiveUrl = itemInfo.primitiveUrl;
                info.prompt = itemInfo.prompt;
                info.type = itemInfo.type;
                break;
            }
        }
    }

    public float getPreviewScale() {
        return mPreviewScale;
    }

    public synchronized PosetemInfo getItemInfoFromSharedPreference(String type) {
        String jStr = mSharedPref.getString(type, null);
        PosetemInfo itemInfo = null;
        if (jStr == null) {
            List<String> tags = PoseResouceId.PAGE_ARRAY_TAG.get(type);
            String tag = tags.get(0);
            itemInfo = PoseResouceId.ITEM_RESOURCE_IDS.get(tag);
            itemInfo.setType(type);
            itemInfo = copyWatermarkItemInfo(itemInfo);
        } else {
            itemInfo = PoseUtil.jsonStrToItemInfo(jStr);
            Log.i("list", "itemInfo:" + itemInfo + ",jStr" + jStr);
            if (itemInfo == null) {
                List<String> tags = PoseResouceId.PAGE_ARRAY_TAG.get(type);
                String tag = tags.get(0);
                itemInfo = PoseResouceId.ITEM_RESOURCE_IDS.get(tag);
                itemInfo.setType(type);
                itemInfo = copyWatermarkItemInfo(itemInfo);
            }
        }
        if (itemInfo.thumbnailId == 0 || itemInfo.primitiveId == 0) {
            boolean isExist = PoseUtil.isFileExistByFileUrl(itemInfo.thumbnailUrl);
            if (isExist) {
                isExist = PoseUtil.isFileExistByFileUrl(itemInfo.primitiveUrl);
            }

            if (!isExist) {
                List<String> tags = PoseResouceId.PAGE_ARRAY_TAG.get(type);
                String tag = tags.get(0);
                itemInfo = PoseResouceId.ITEM_RESOURCE_IDS.get(tag);
                itemInfo.setType(type);
                itemInfo = copyWatermarkItemInfo(itemInfo);
            }
        }
        addItemToPreviewItemList(itemInfo);
        return itemInfo;
    }

    public PoseMode() {
        super();
    }

    public PoseMode(Context c, String pkgName) {
        super(c, pkgName);
        mPackageName = pkgName;
        clearPreviewItemList();
        mLayoutInflater = LayoutInflater.from(mContext);
        mLayoutInflater.setFactory(new Factory() {
            @Override
            public View onCreateView(String name, Context context, AttributeSet attrs) {
                if ("com.freeme.cameraplugin.posemode.ui.RotateLayout".equals(name)) {
                    return new RotateLayout(context, attrs);
                } else if ("com.freeme.cameraplugin.posemode.ui.PosePreviewPanel".equals(name)) {
                    return new PosePreviewPanel(context, attrs);
                } else if ("android.support.v4.view.ViewPager".equals(name)) {
                    return new ViewPager(context, attrs);
                } else if ("com.freeme.cameraplugin.posemode.ui.PoseViewPager".equals(name)) {
                    return new PoseViewPager(context, attrs);
                } else if ("com.freeme.cameraplugin.posemode.ui.RotateImageView".equals(name)) {
                    return new RotateImageView(context, attrs);
                } else if ("com.freeme.cameraplugin.posemode.ui.RotataTextView".equals(name)) {
                    return new RotataTextView(context, attrs);
                }
                return null;
            }
        });
    }

    private void initPose() {
        initPreviewPanel();
    }

    public boolean readOfflineNewStatus(String key, boolean defaultVal) {
        return mSharedPref.getBoolean(key, defaultVal);
    }

    public void saveOfflineNewStatus(String key, boolean value) {
        SharedPreferences.Editor editor = mSharedPref.edit();
        editor.putBoolean(key, value);
        editor.commit();
    }

    /**
     * Whether affect watermark
     *
     * @return
     */
    public boolean isOn() {
        boolean result = false;
        return result;
    }

    public void hide() {
        if (mRootView == null || mPreviewPanel == null) {
            return;
        }
        mRootView.removeView(mPreviewPanel);
        mPreviewPanel.destroyDrawingCache();
        mPreviewPanel = null;
    }

    public void show(ViewGroup root) {
        mRootView = root;
        Log.i(TAG, "show");
        initPose();
    }

    public boolean isShowGuide() {
        return false;
    }

    public void popupSettingPanel() {
    }

    public String getCurrentAddr() {
        return mAddr;
    }

    public void initPreviewPanel() {
        if (mRootView == null) {
            return;
        }
        if (mPreviewPanel == null) {
            mPreviewPanel = (PosePreviewPanel) mLayoutInflater.inflate(
                    R.layout.pose_preview_page_panel, null);
            mTextEcDownLoad = (LinearLayout) mPreviewPanel.findViewById(R.id.ec_download);
            mTextEcDownLoad.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    try {
                        Intent intent = new Intent("freeme.intent.action.freeme.ec");
                        intent.putExtra(ECOfflineUtil.TYPE_CODE_TAG, ECOfflineUtil.POSE_TYPE_CODE);
                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
                                | Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        mContext.startActivity(intent);
                    } catch (Exception e) {
                        Toast.makeText(mContext, R.string.startup_ec_tip, Toast.LENGTH_SHORT)
                                .show();
                    }
                }
            });
            RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
                    RelativeLayout.LayoutParams.MATCH_PARENT,
                    RelativeLayout.LayoutParams.WRAP_CONTENT);
            lp.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
            lp.addRule(RelativeLayout.CENTER_HORIZONTAL);
            mRootView.addView(mPreviewPanel, lp);
            mPreviewPanel.init(mCameraExt, this);
            setOrientation(mPreviewPanel, mOrientation, true);
        }
    }
}
